package com.neuedu.web.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author 金山
 * 项目：javaweb
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2024/11/158:59
 */
@WebServlet("/loginbak")
public class LoginControllerBak extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {


        //获取session对象
        HttpSession session = request.getSession();
        // session.set
        System.out.println("session.getId() = " + session.getId());

        // response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Origin", "http://localhost");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        boolean isLogin = false;
        // 获取从客户端发送过来的Cookie（获取的是一个Cookie数组）
        Cookie[] cookieArr = request.getCookies();
        if(cookieArr!=null) {
            //遍历每一个cookie的名称（使用getName()方法）
            for(Cookie cookie : cookieArr) {
                if(cookie.getName().equals("user")) {
                    System.out.println("自动登陆成功");
                    isLogin = true;
                }
            }
        }
        if(!isLogin) {
            String userName = request.getParameter("userName");
            String password = request.getParameter("password");
            if(userName.equals("admin")&&password.equals("123456")) {
                System.out.println("登陆成功");
                //创建用户信息Cookie
                Cookie userCookie = new Cookie("user","ok");
                //设置Cookie过期时间为一周
                userCookie.setMaxAge(24*60*60);

                //向客户端发生Cookie
                response.addCookie(userCookie);
            }else {
                System.out.println("登陆失败");
            }
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);
    }
}